// 创建浮动下载按钮
const downloadBtn = document.createElement('button');
downloadBtn.textContent = '下载';
downloadBtn.style.position = 'fixed';
downloadBtn.style.bottom = '20px';
downloadBtn.style.right = '20px';
downloadBtn.style.zIndex = '9999';
downloadBtn.style.padding = '10px 20px';
downloadBtn.style.backgroundColor = '#4CAF50';
downloadBtn.style.color = 'white';
downloadBtn.style.border = 'none';
downloadBtn.style.borderRadius = '4px';
downloadBtn.style.cursor = 'pointer';

// 点击事件处理
downloadBtn.addEventListener('click', async () => {
    let attempts = 0;
    let cur_placeholderCount = document.querySelectorAll('div#reader-scroll img[src*="/static/images/zw.png"]').length;
    if (cur_placeholderCount==0){return}
    while (cur_placeholderCount > 0) {
        attempts++;
        let list = document.querySelectorAll('div#reader-scroll img[src*="/static/images/zw.png"]');
        let scrollElement = list.length > 8 ? list[7] : list[0];
        
        await new Promise(resolve => setTimeout(resolve, 1000));
        scrollElement.scrollIntoView({
            behavior: 'smooth',
            block: 'end'
        });
        
        cur_placeholderCount = document.querySelectorAll('div#reader-scroll img[src*="/static/images/zw.png"]').length;
        console.log(`滚动尝试 ${attempts}, 剩余placeholder图片: ${cur_placeholderCount}`);
    }

    const images = document.querySelectorAll('div#reader-scroll img');
    const chapterID = window.location.href.match(/artdetail-(\d+)-(\d+)/)[2];
    const comicID = window.location.href.match(/artdetail-(\d+)-(\d+)/)[1];
    const chapterName = document.querySelector('#js_headChapterName').innerHTML.trim().replace(/\?/g, '');
    const chapterFolder = chapterID.padStart(3, '0')//+'-'+chapterName;
    const comicName = document.title.split('-')[0].trim();

    // 创建单个canvas复用
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    
    try {
        for (let i = 0; i < images.length; i++) {
            const img = images[i];
            canvas.width = img.naturalWidth;
            canvas.height = img.naturalHeight;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.drawImage(img, 0, 0);

            const dataURL = canvas.toDataURL('image/png');
            const filename = `${comicName}/${chapterFolder}/${(i + 1).toString().padStart(2, '0')}.jpg`;

            await new Promise((resolve) => {
                //若慈航报错，或者不能下载，可能是章节名称里有特殊字符导致创建文件夹失败，下载失败
                chrome.runtime.sendMessage({
                    action: 'requestDownload',
                    dataURL: dataURL,
                    filename: filename
                }, (response) => {
                    resolve();
                });
            });

            if (i % 10 === 0) {
                window.gc && window.gc();
            }
        }
    } finally {
        delete canvas,ctx;

    }

    const currentPage = parseInt(chapterID);
    const nextPage = currentPage + 1;
    const nextUrl = window.location.href.replace(/artdetail-\d+-(\d+)/, `artdetail-${comicID}-${nextPage}`);
    window.location.href = nextUrl;
});

if (!document.getElementById('comic-download-btn')) {
    downloadBtn.id = 'comic-download-btn';
    document.body.appendChild(downloadBtn);
}
downloadBtn.click()
// 监听来自background.js的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.action === 'downloadComplete') {
        console.log(message.status ? '下载成功' : '下载失败');
    }
});
